package org.journey.datasouece;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Configuration
public class DataSourceConfig {

    @Autowired
    DataSourceProperties dataSourceProperties;

    @Primary
    @Bean(name = DataSourceConstants.DEFAULT_DATA_SOURCE_NAME)
    @Qualifier(DataSourceConstants.DEFAULT_DATA_SOURCE_NAME)
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class)
                .url(dataSourceProperties.getJdbcUrl().replace(DataSourceConstants.DATA_SOURCE_NAME_REG,""))
                .driverClassName(dataSourceProperties.getDriverClassName())
                .username(dataSourceProperties.getUsername())
                .password(dataSourceProperties.getPassword())
                .build();
    }


    @Bean(name = DataSourceConstants.MULTI_TENANT_DATA_SOURCE_NAME)
    @Qualifier(DataSourceConstants.MULTI_TENANT_DATA_SOURCE_NAME)
    public AbstractRoutingDataSource multiDataSourceProxy() {
        MultiTenantDataSource proxy = new MultiTenantDataSource(
                dataSourceProperties.getJdbcUrl(),
                dataSourceProperties.getDriverClassName(),
                dataSourceProperties.getUsername(),
                dataSourceProperties.getPassword()
        );
        ConcurrentHashMap<Object, Object> targetDataSources = new ConcurrentHashMap<Object, Object>();
        targetDataSources.put("", dataSource());
        proxy.setDefaultTargetDataSource(dataSource());
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }

}
